/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sree.tali.filter;

import com.sree.tali.buscomp.DisplayBusComp;
import com.sree.tali.buscomp.DisplayBusCompImpl;
import com.sree.tali.plugin.HibernatePlugin;
import com.sree.tali.pojo.LoginForm;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import org.hibernate.SessionFactory;

// Implements Filter class
public class RolesCheck implements Filter {
      private  ServletContext application= null;
    public void init(FilterConfig config)
            throws ServletException {
      // Get init parameter 
       application =config.getServletContext();
        //Print the init parameter 
    }

    public void doFilter(ServletRequest request,
            ServletResponse response,
            FilterChain chain)
            throws java.io.IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;
   

        // Get the IP address of client machine.   
        String ipAddress = request.getRemoteAddr();

        // Log the IP address and current timestamp.
        System.out.println("IP " + ipAddress);
        boolean isValid=false;
        LoginForm loginform = (LoginForm) httpReq.getSession().getAttribute("loginform");
        if (loginform != null) {
            DisplayBusComp localDisplayBusCompImpl = new DisplayBusCompImpl();
            SessionFactory localSessionFactory = (SessionFactory) application.getAttribute(HibernatePlugin.KEY_NAME);

            if (localDisplayBusCompImpl.AuthenticateIp(localSessionFactory.openSession(), request.getRemoteAddr())) {
                 isValid = localDisplayBusCompImpl.Authenticate(localSessionFactory.openSession(), loginform);
            }
        }

        //chain.doFilter(request,response);
        if(!isValid){
        request.getRequestDispatcher("/SreeLogin.jsp").forward(request, response);
        }
        else
             chain.doFilter(request,response);
        //response.getWriter().
    }

    public void destroy() {
        /* Called before the Filter instance is removed 
         from service by the web container*/
    }
}
